package org.lee.domain.service.engine;

import org.lee.domain.model.aggregates.TreeRich;
import org.lee.domain.model.vo.EngineResult;
import org.lee.domain.model.vo.NodeType;
import org.lee.domain.model.vo.TreeNode;
import org.lee.domain.model.vo.TreeRoot;
import org.lee.domain.service.logic.ILogicFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * EngineBase
 * 决策引擎基类
 * @author dralee
 * @date 2021-11-22 14:11:30
 **/
public abstract class EngineBase extends EngineConfig implements IEngine{

    private final Logger logger = LoggerFactory.getLogger(EngineBase.class);

    @Override
    public abstract EngineResult process(long treeId, String userId, TreeRich treeRich, Map<String, String> decisionMatter);

    protected TreeNode engineDecisionMaker(TreeRich treeRich, long treeId, String userId, Map<String, String> decisionMatter){
        TreeRoot root = treeRich.getTreeRoot();
        Map<Long, TreeNode> nodeMap = treeRich.getTreeNodeMap();
        long rootNodeId = root.getTreeRootNodeId();
        TreeNode node = nodeMap.get(rootNodeId);
        // 节点类型：子叶，果实
        while (node.getNodeType() == NodeType.LEAF){
            String ruleKey = node.getRuleKey();
            ILogicFilter logicFilter = logicFilterMap.get(ruleKey);
            String matterValue = logicFilter.matterValue(treeId, userId, decisionMatter);
            long nextNode = logicFilter.filter(matterValue, node.getTreeNodeLinkList());
            node = nodeMap.get(nextNode);
            logger.info("决策树引擎=>{} user:{}, treeId:{}, treeNode:{}, ruleKey:{}, matterValue:{}", root.getTreeName(), userId, treeId, node.getTreeNodeId(), ruleKey, matterValue);
        }

        return node;
    }
}
